package com.atguigu.flink.window;

import com.atguigu.flink.function.MyUtil;
import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * Created by Smexy on 2023/2/27
 *
 *  处理时间: 参考计算机的物理时钟
 */
public class Demo3_TimeWindowAll
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   //5s的滚动窗口  每5s算一次，一次算过去5s中到达的数据 举例: [0,5) , [5,10)
                   //.windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                   // 5s的滑动窗口， 5s算一次，一次算过去10s到达的数据 举例: [-5,5) , [0,10) ,[5,15)
                   //.windowAll(SlidingProcessingTimeWindows.of(Time.seconds(10),Time.seconds(5)))
                   // 5s间隔的会话窗口。 两个元素的时间间隔超过5s，处于两个窗口，不超过就处于一个窗口。 窗口的size是不确定的！
                   .windowAll(ProcessingTimeSessionWindows.withGap(Time.seconds(5)))
                   // 基于时间的窗口，函数的最后一个参数类型一定是 TimeWindow，自带一组 [start,end)
                   .process(new ProcessAllWindowFunction<WaterSensor, String, TimeWindow>()
                   {
                       @Override
                       public void process(Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                           List<WaterSensor> waterSensors = MyUtil.parseToList(elements);

                           TimeWindow timeWindow = context.window();
                           out.collect(MyUtil.parseTimeWindow(timeWindow) + ":"+waterSensors.toString());
                       }
                   })
                   .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
    }
}
